package com.example.campus_order_sb.service;

import com.example.campus_order_sb.dto.LoginRequest;
import com.example.campus_order_sb.dto.LoginResponse;
import com.example.campus_order_sb.dto.RegisterRequest;
import com.example.campus_order_sb.dto.RegisterResponse;
import com.example.campus_order_sb.entity.User;
import com.example.campus_order_sb.enums.UserType;
import com.example.campus_order_sb.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public LoginResponse login(LoginRequest request) {
        Optional<User> userOpt = userRepository.findByUsername(request.getUsername());

        if (userOpt.isEmpty()) {
            return new LoginResponse("用户不存在", false);
        }

        User user = userOpt.get();
        if (!user.getPassword().equals(request.getPassword())) {
            return new LoginResponse("密码错误", false);
        }

        // 返回用户ID和用户类型
        return new LoginResponse(user.getId(), user.getUserType().toString());
    }

    public RegisterResponse register(RegisterRequest request) {
        // 检查用户名是否已存在
        Optional<User> existingUser = userRepository.findByUsername(request.getUsername());
        if (existingUser.isPresent()) {
            return new RegisterResponse("用户名已被使用", false);
        }

        // 检查邮箱是否已存在
        Optional<User> existingEmail = userRepository.findByEmail(request.getEmail());
        if (existingEmail.isPresent()) {
            return new RegisterResponse("邮箱已被注册", false);
        }

        // 创建新用户
        User user = new User();
        user.setEmail(request.getEmail());
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword());
        user.setUserType(UserType.STUDENT);

        // 保存用户
        userRepository.save(user);

        return new RegisterResponse("注册成功");
    }
}